package cmdServer

import (
	"bufio"
	"encoding/base64"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"remote-go/server/data"
	"remote-go/server/util"
	"remote-go/utils"
)

var (
	downloadOutName string
)

func SendDownload(ok bool, conn net.Conn) {
	if ok {
		// 第一步,发送下载指令
		encDownload := base64.URLEncoding.EncodeToString([]byte("download"))
		conn.Write([]byte(encDownload + "\n"))
		// 第二步，输入下载路径和要保存的文件名,发送给客户端
		fmt.Print("File Path to Download: ")
		nameDownload := util.ReadLine()
		// 第三步，输入本地电脑保存的文件名
		fmt.Print("Output name: ")
		downloadOutName = util.ReadLine()
		// 下发需要download的文件名路径, conn连接的协程里面接收
		encName := base64.URLEncoding.EncodeToString([]byte(nameDownload))
		conn.Write([]byte(encName + "\n"))
		fmt.Print(encName)
	} else {
		fmt.Println("请重新选择客户端, help查看帮助")
	}
}

func AcceptDownload(conn net.Conn) {
	//fmt.Println("---收到download指令，等待下一次数据上传---")
	// 等待用户上传数据
	encData, _ := bufio.NewReader(conn).ReadString('\n')
	fmt.Println(data.YELLOW, "-> Downloading...")
	decData, _ := base64.URLEncoding.DecodeString(encData)
	downName := downloadOutName + "_" + util.GetDateTime()
	downFilePath, _ := filepath.Abs(filepath.Join("temp", downName))
	utils.CreateBaseDir(downFilePath)
	os.WriteFile(downFilePath, decData, 777)
	fmt.Println(data.GREEN, "-> Download Done...")
}
